package com.woniu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.constants.RedisConstants;
import com.woniu.constants.WeChatConstants;
import com.woniu.entity.WechatTemplateMessage;
import com.woniu.mapper.RedPacketPoolMapper;
import com.woniu.mapper.WechatTemplateMessageMapper;
import com.woniu.service.WechatService;
import com.woniu.service.WechatTemplateMessageService;
import com.woniu.utils.RedisUtil;
import com.woniu.utils.TimeUtil;
import com.woniu.vo.ProgramTemplateMessageVo;
import com.woniu.vo.PublicCustomProgramMessageVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description:
 * @Author: woniu
 * @date: 2024/1/12 13:40
 */
@Slf4j
@Service
public class WechatTemplateMessageServiceImpl extends ServiceImpl<WechatTemplateMessageMapper, WechatTemplateMessage> implements WechatTemplateMessageService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private RedPacketPoolMapper redPacketPoolMapper;

    /**
     * 公众号消费队列消费
     */
    @Override
    public void consumePublic() {
        String redisKey = WeChatConstants.WE_CHAT_MESSAGE_KEY_PUBLIC;
        Long size = redisUtil.getListSize(redisKey);
        log.info("TemplateMessageServiceImpl.consumePublic | size:" + size);
        if(size < 1){
            return;
        }
        for (int i = 0; i < size; i++) {
            //如果10秒钟拿不到一个数据，那么退出循环
            Object data = redisUtil.getRightPop(redisKey, 10L);
            if(null == data){
                continue;
            }
            try{
                ProgramTemplateMessageVo templateMessage = JSONObject.toJavaObject(JSONObject.parseObject(data.toString()), ProgramTemplateMessageVo.class);
                boolean result = wechatService.sendPublicTemplateMessage(templateMessage);
//                boolean result = weChatService.sendPublicTempMessage(templateMessage);
                if(!result){
                    redisUtil.lPush(redisKey, data);
                }
            }catch (Exception e){
                redisUtil.lPush(redisKey, data);
            }
        }
    }

    /**
     * 公众号客服消息消费队列消费
     */
    @Override
    public void consumeCustomPublic() {
        // 先查询是否可以发送通知
        String sendKey = RedisConstants.REDPACKET_SEND_PUBLIC;
        if (!redisUtil.exists(sendKey)){
            return;
        }
        // 删除红包通知
        else {
            redisUtil.delete(sendKey);
        }


        String redisKey = WeChatConstants.WE_CHAT_CUSTOM_KEY_PUBLIC;
        Long size = redisUtil.getListSize(redisKey);
        log.info("TemplateMessageServiceImpl.consumeCustomPublic | size:" + size);
        if(size < 1){
            return;
        }
        String nowStartDate = TimeUtil.getNowStartDate();
        String nowEndDate = TimeUtil.getNowEndDate();
        for (int i = 0; i < size; i++) {
            //如果10秒钟拿不到一个数据，那么退出循环
            Object data = redisUtil.getRightPop(redisKey, 10L);
            if(null == data){
                continue;
            }
            try{
                PublicCustomProgramMessageVo publicCustomProgramMessageVo = JSONObject.toJavaObject(JSONObject.parseObject(data.toString()), PublicCustomProgramMessageVo.class);

                // 查询用户今日是否已中过红包
                if (redPacketPoolMapper.existReceivedByNowDateAndUopenid(nowStartDate,nowEndDate, publicCustomProgramMessageVo.getTouser())){
                    return;
                }

                boolean result = wechatService.sendPulicCustomProgramMessage(publicCustomProgramMessageVo);
//                boolean result = weChatService.sendPublicTempMessage(templateMessage);
//                if(!result){
//                    redisUtil.lPush(redisKey, data);
//                }
            }catch (Exception e){
                redisUtil.lPush(redisKey, data);
            }
        }
    }

    /**
     * 小程序消费队列消费
     */
    @Override
    public void consumeProgram() {
        String redisKey = WeChatConstants.WE_CHAT_MESSAGE_KEY_PROGRAM;
        Long size = redisUtil.getListSize(redisKey);
        log.info("TemplateMessageServiceImpl.consumeProgram | size:" + size);
        if(size < 1){
            return;
        }

        // 任务开始时间
        long startTimeMillis = System.currentTimeMillis();
        // 时间块
        int timeNum = 0;
        // 发送数量
        int sendNum = 0;

        for (int i = 0; i < size; i++) {
            //如果10秒钟拿不到一个数据，那么退出循环
            Object data = redisUtil.getRightPop(redisKey, 10L);
            if(null == data){
                continue;
            }



            try{
                // 每5分钟就记录一次
                long diffTime = System.currentTimeMillis() - startTimeMillis;
                if (diffTime / 300000 > timeNum){
                    timeNum++;
                }
                // 如果5分钟内发送的数量大于5K，就睡眠够5分钟
                if (sendNum / 5000 > timeNum){
                    Thread.sleep(diffTime-(300000L * (timeNum +1)));
                }

                ProgramTemplateMessageVo templateMessage = JSONObject.toJavaObject(JSONObject.parseObject(data.toString()), ProgramTemplateMessageVo.class);
                boolean result = wechatService.sendMiniSubscribeMessage(templateMessage);
                sendNum++;
//                if(!result){
//                    redisUtil.lPush(redisKey, data);
//                }else {
//                    sendNum++;
//                }
            }catch (Exception e){
                redisUtil.lPush(redisKey, data);
            }
        }
    }

}
